package oneplay.YonghongBITools.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Properties;

@Slf4j
public class PropertiesUtil {
    private final static Properties properties = new Properties();

    static {
        try {
            properties.load(getInputStream("src/main/resources/application.properties"));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

    /**
     * 获取配置文件输入流
     */
    public static InputStreamReader getInputStream(String filename) {
        String[] paths = new String[]{
                filename, // 当前目录下
                "conf" + File.separator + filename, // 当前目录conf文件夹下
                "src/main" + File.separator + "conf" + File.separator + filename  // 父级目录conf文件夹下
        };
        InputStream inputStream;
        try {
            for (String path : paths) {
                File file = new File(path);
                if (file.exists()) {
                    inputStream = Files.newInputStream(file.toPath());
                    return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                }
            }
        } catch (IOException ignored) {
        }
        inputStream = InputStreamReader.class.getResourceAsStream("/" + filename);
        assert inputStream != null;
        return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    }

}
